package com.dqhl.business.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.business.Base.BaseFragment;
import com.dqhl.business.R;
import com.dqhl.business.activity.AddGoodsActivity;
import com.dqhl.business.activity.AddGoodsTypeActivity;
import com.dqhl.business.activity.GoodsDetailsEditActivity;
import com.dqhl.business.activity.GoodsManagerRecordActivity;
import com.dqhl.business.activity.GoodsTypeClassifyActivity;
import com.dqhl.business.adapter.GoodsManagerAdapter;
import com.dqhl.business.adapter.GoodsTypeAdapter;
import com.dqhl.business.modle.GoodsManager;
import com.dqhl.business.modle.GoodsType;
import com.dqhl.business.util.Config;
import com.dqhl.business.util.Constant;
import com.dqhl.business.util.Dlog;
import com.dqhl.business.util.JsonUtils;
import com.dqhl.business.view.GoodsManagerOperationDownPopWindow;
import com.dqhl.business.view.GoodsManagerOperationUpPopWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

/**
 * Created by mac on 16/11/2.
 * 管理 Fragment
 */
public class ManagementFragment extends BaseFragment implements View.OnClickListener, GoodsManagerAdapter.OnOperationListener {

    private ImageView iv_upGoods;//上架
    private ImageView iv_downGoods;//下架
    private ImageView iv_goodsType;//分类筛选
    private List<GoodsManager> goodsManagerList;
    private List<GoodsType> goodsTypeList;
    private GoodsManagerAdapter goodsManagerAdapter;
    private GoodsTypeAdapter goodsTypeAdapter;
    private TextView tv_no_data;
    private ListView lv_goodsManager;//上架下架商品
    private ListView lv_type;//分类管理
    private GoodsManagerOperationDownPopWindow operationPopWindow;
    private GoodsManagerOperationUpPopWindow operationUpPopWindow;
    private View view;
    private Context context;
    private static final int RESULTCODE = 101;
    private final int REQUEST_CODE = 1;

    private LinearLayout ll_goods;
    private LinearLayout ll_goodsType;
    private ImageView iv_managerType;
    private ImageView iv_addType;
    private ImageView iv_addGoods;
    private String flag = "1";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        context = getActivity();
        view = inflater.inflate(R.layout.fragment_management, container, false);
        initView(view);
        initGoods("1");

        registerBroadcastReceiver();
        return view;
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_EDIT_GOODS)) {
                if ("1".equals(flag)) {
                    initGoods("1");
                } else {
                    initGoods("2");
                }
            } else if (action.equals(Constant.ACTION_ADD_GOODS)) {
                if ("1".equals(flag)) {
                    initGoods("1");
                } else {
                    initGoods("2");
                }
            }
        }
    };

    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_EDIT_GOODS);
        intentFilter.addAction(Constant.ACTION_ADD_GOODS);
        getActivity().registerReceiver(receiver, intentFilter);
    }

    private void initView(View view) {
        (iv_upGoods) = (ImageView) view.findViewById(R.id.iv_upGoods);
        (iv_downGoods) = (ImageView) view.findViewById(R.id.iv_downGoods);
        (iv_goodsType) = (ImageView) view.findViewById(R.id.iv_goodsType);
        (lv_goodsManager) = (ListView) view.findViewById(R.id.lv_goodsManager);
        (ll_goods) = (LinearLayout) view.findViewById(R.id.ll_goods);
        (ll_goodsType) = (LinearLayout) view.findViewById(R.id.ll_goodsType);
        tv_no_data = (TextView) view.findViewById(R.id.tv_no_data);
        (lv_type) = (ListView) view.findViewById(R.id.lv_type);
        (iv_managerType) = (ImageView) view.findViewById(R.id.iv_managerType);
        (iv_addType) = (ImageView) view.findViewById(R.id.iv_addType);
        iv_addGoods = (ImageView) view.findViewById(R.id.iv_addGoods);
        iv_upGoods.setOnClickListener(this);
        iv_downGoods.setOnClickListener(this);
        iv_goodsType.setOnClickListener(this);
        iv_addType.setOnClickListener(this);
        iv_managerType.setOnClickListener(this);
        iv_addGoods.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //上架
            case R.id.iv_upGoods:
                flag = "1";
                ll_goods.setVisibility(View.VISIBLE);
                ll_goodsType.setVisibility(View.GONE);
                initGoods("1");
                iv_upGoods.setImageResource(R.drawable.ic_goods_up_pressed);
                iv_downGoods.setImageResource(R.drawable.ic_goods_down);
                break;
            //下架
            case R.id.iv_downGoods:
                flag = "2";
                ll_goods.setVisibility(View.VISIBLE);
                ll_goodsType.setVisibility(View.GONE);
                initGoods("2");
                iv_upGoods.setImageResource(R.drawable.ic_goods_up);
                iv_downGoods.setImageResource(R.drawable.ic_goods_down_pressed);
                break;
            //分类筛选
            case R.id.iv_goodsType:
                ll_goods.setVisibility(View.GONE);
                ll_goodsType.setVisibility(View.VISIBLE);
                initTypeSelect();
                iv_upGoods.setImageResource(R.drawable.ic_goods_up);
                iv_downGoods.setImageResource(R.drawable.ic_goods_down);
                break;
            //添加分类
            case R.id.iv_addType:
                overlay(AddGoodsTypeActivity.class, REQUEST_CODE);
                break;
            //分类管理
            case R.id.iv_managerType:
                overlay(GoodsTypeClassifyActivity.class);
                break;
            //添加商品
            case R.id.iv_addGoods:
                overlay(AddGoodsActivity.class);
                break;
        }
    }

    /**
     * 加载数据
     *
     * @param state 商品状态(1上架 2下架)
     */
    private void initGoods(String state) {
        Dlog.e(user.getUser_id() + ";" + state);
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.management_goods_list);
        params.addBodyParameter("seller_id", user.getUser_id());
        params.addBodyParameter("state", state);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (0 == errCode) {
                    tv_no_data.setVisibility(View.GONE);
                    lv_goodsManager.setVisibility(View.VISIBLE);
                    goodsManagerList = JSON.parseArray(data, GoodsManager.class);
                    goodsManagerAdapter = new GoodsManagerAdapter(context, goodsManagerList, ManagementFragment.this);
                    goodsManagerAdapter.notifyDataSetChanged();
                    lv_goodsManager.setAdapter(goodsManagerAdapter);
                } else {
                    tv_no_data.setVisibility(View.VISIBLE);
                    lv_goodsManager.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Dlog.e(ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Dlog.e(cex.toString());
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    //分类筛选
    public void initTypeSelect() {
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.management_goods_type_list);
        params.addBodyParameter("seller_id", user.getUser_id());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (0 == errCode) {
                    tv_no_data.setVisibility(View.GONE);
                    lv_type.setVisibility(View.VISIBLE);
                    goodsTypeList = JSON.parseArray(data, GoodsType.class);
                    goodsTypeAdapter = new GoodsTypeAdapter(context, goodsTypeList);
                    goodsTypeAdapter.notifyDataSetChanged();
                    lv_type.setAdapter(goodsTypeAdapter);
                    lv_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", goodsTypeList.get(i).getId());
                            overlay(GoodsManagerRecordActivity.class, bundle);
                        }
                    });
                } else {
                    tv_no_data.setVisibility(View.VISIBLE);
                    lv_type.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    //商品操作
    @Override
    public void onOperation(final int position) {
        // 1  上架状态  2  下架状态
        if ("1".equals(flag)) {
            //下架pop
            operationUpPopWindow = new GoodsManagerOperationUpPopWindow(getActivity(),
                    goodsManagerList.get(position).getOpen(),
                    new GoodsManagerOperationUpPopWindow.OnOperationListener() {
                        @Override
                        public void onEditGoods() { //编辑
                            operationUpPopWindow.dismiss();
                            Bundle bundle = new Bundle();
                            bundle.putString("goods_id", goodsManagerList.get(position).getId());
                            overlay(GoodsDetailsEditActivity.class, bundle);
                        }

                        @Override
                        public void onDownGoods() { //下架
                            modifyGoodsState(goodsManagerList.get(position).getId(), "2", null);
                            operationUpPopWindow.dismiss();
                        }

                        @Override
                        public void onForbidGoods() { //禁用
                            if ("1".equals(goodsManagerList.get(position).getOpen())) {
                                modifyGoodsState(goodsManagerList.get(position).getId(), null, "2");
                            } else {
                                modifyGoodsState(goodsManagerList.get(position).getId(), null, "1");
                            }
                            operationUpPopWindow.dismiss();
                        }

                        @Override
                        public void onCancelGoods() { //取消
                            operationUpPopWindow.dismiss();
                        }
                    });
            operationUpPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    operationUpPopWindow.backgroundAlpha(1.0f);
                }
            });
            operationUpPopWindow.showAtLocation(view.findViewById(R.id.ll_goodsManager), Gravity.BOTTOM, 0, 0);
            operationUpPopWindow.backgroundAlpha(0.5f);
        } else {
            //上架pop
            operationPopWindow = new GoodsManagerOperationDownPopWindow(getActivity(),
                    goodsManagerList.get(position).getOpen(),
                    new GoodsManagerOperationDownPopWindow.OnOperationListener() {
                        @Override
                        public void OnEditGoods() { //编辑
                            Bundle bundle = new Bundle();
                            Dlog.e(goodsManagerList.get(position).getId());
                            bundle.putString("goods_id", goodsManagerList.get(position).getId());
                            overlay(GoodsDetailsEditActivity.class, bundle);
                            operationPopWindow.dismiss();
                        }

                        @Override
                        public void OnUpGoods() { //上架
                            modifyGoodsState(goodsManagerList.get(position).getId(), "1", null);
                            operationPopWindow.dismiss();
                        }

                        @Override
                        public void onForbidGoods() { //禁用
                            if ("1".equals(goodsManagerList.get(position).getOpen())) {
                                modifyGoodsState(goodsManagerList.get(position).getId(), null, "2");
                            } else {
                                modifyGoodsState(goodsManagerList.get(position).getId(), null, "1");
                            }
                            operationPopWindow.dismiss();
                        }

                        @Override
                        public void onCancelGoods() { //取消
                            operationPopWindow.dismiss();
                        }
                    });
            operationPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    operationPopWindow.backgroundAlpha(1.0f);
                }
            });
            operationPopWindow.showAtLocation(view.findViewById(R.id.ll_goodsManager), Gravity.BOTTOM, 0, 0);
            operationPopWindow.backgroundAlpha(0.5f);
        }
    }

    /**
     * 修改商品的状态(上下架,禁用)
     *
     * @param goodsId 商品ID
     * @param state   商品状态(1 上架 2下架)
     * @param open    商品是否禁用(1 启用 2禁用)
     */
    private void modifyGoodsState(String goodsId, final String state, String open) {
        showCustomLoadBar(".");
        Dlog.e("修改商品的状态:" + goodsId + ";" + state + ";" + open);
        RequestParams params = new RequestParams(Config.management_goods_moify_status);
        params.addBodyParameter("id", goodsId);
        params.addBodyParameter("state", state);
        params.addBodyParameter("open", open);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (0 == errCode) {
                    if ("1".equals(flag)) {
                        initGoods("1");
                    } else {
                        initGoods("2");
                    }
                } else {
                    toast(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULTCODE) {
            String name = data.getStringExtra("typeName");
            String id = data.getStringExtra("id");
            GoodsType goodsType = new GoodsType();
            goodsType.setName(name);
            goodsType.setId(id);
            goodsType.setAuditing("1");
            goodsType.setCount("0");
            goodsTypeList.add(goodsType);
            goodsTypeAdapter = new GoodsTypeAdapter(context, goodsTypeList);
            goodsTypeAdapter.notifyDataSetChanged();
            lv_type.setAdapter(goodsTypeAdapter);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            getActivity().unregisterReceiver(receiver);
        }
    }
}
